#pragma once

#include<iostream>
#include<unordered_map>
#include<functional>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>

using task_t = std::function<void()>;

void Download()
{
    std::cout<<"我是下载任务...,pid="<<::getpid()<<std::endl;
}
void Log()
{
    std::cout<<"我是日志任务...,pid="<<::getpid()<<std::endl;
}
void Sql()
{
    std::cout<<"我是数据库同步任务...,pid="<<::getpid()<<std::endl;
}

static int number = 0;
class TaskManager
{
public:
    TaskManager()
    {
        srand(time(nullptr));
        InsertTask(Sql);
        InsertTask(Log);
        InsertTask(Download);
    }
    void InsertTask(task_t t)
    {
        _tasks[number++] = t;
    }

    int SelectTask()
    {
        return rand()%number;
    }

    void Execute(int num)
    {
        if(_tasks.find(num) == _tasks.end())return;
        _tasks[num]();
    }
    ~TaskManager()
    {
        
    }


private:
    std::unordered_map<int,task_t> _tasks;//任务
} tm;

// 子进程做的任务
void Worker()
{
    while (true)
    {
        int cmd = 0;
        // 从标准输入读出数据
        int n = ::read(0, &cmd, sizeof cmd);
        if (n == sizeof cmd)
        {
            tm.Execute(cmd);
        }
        else if (n == 0)
        {
            //读到文件结尾
            std::cout<<"pid: "<<getpid()<<std::endl;
            break;
        }
        else
        {
        }
    }
}